
package cn.zniot.so.application.util;

import cn.zniot.so.application.constant.Constants;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;

public class SocketUtil {

    private  String clientIp;
    private  String clientPort;
    private static final Log logger = LogFactory.getLog(SocketUtil.class);

    public  String getClientIp() {
        return clientIp;
    }

    public  void setClientIp(String clientIp) {
        this.clientIp = clientIp;
    }

    public  String getClientPort() {
        return clientPort;
    }

    public  void setClientPort(String clientPort) {
        this.clientPort = clientPort;
    }

    public String socketClient(String xml) {
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream is = null;
        try {
            socket = new Socket(Constants.CMD_IP, Constants.CMD_PORT);
            socket.setSoTimeout(4000);
            outputStream = socket.getOutputStream();

            outputStream.write(xml.getBytes());
            outputStream.flush();
            is = socket.getInputStream();
            byte[] bytes = new byte[4096];
            int n = is.read(bytes);
            byte[] r = new byte[n];
            r = Arrays.copyOf(bytes, n);
            return new String(r, "UTF8");
        } catch (Exception e) {
            logger.error(e);
        } finally {

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
